#!/bin/bash
# vim:ts=4:sw=4:noexpandtab
#
# Parallels userspace applications startup script.
#
# Copyright (c) 2004-2014 Parallels IP Holdings GmbH.
# All rights reserved.
# http://www.parallels.com


export PATH=/bin:/sbin:/usr/bin:/usr/sbin

SCRIPT_NAME="$(basename "$0")"

TIME_FOR_SLEEP=0.05

BUNDLE_DIR="$(cd "`dirname "${0}"`/../.."; pwd)"
BUNDLE_CONTENTS_DIR="${BUNDLE_DIR}/Contents"

SERVICES_PATH="${BUNDLE_CONTENTS_DIR}/MacOS"

PARALLELS_EVENT_TAP="${SERVICES_PATH}/prl_event_tap"
PARENTAL_CONTROL="${SERVICES_PATH}/prl_naptd"

# Agents
declare -a AGENTS
AGENTS+=("${PARALLELS_EVENT_TAP}" "")
AGENTS+=("${PARENTAL_CONTROL}" "proxy")
###

RT_ROOT=
PARALLELS_HOME_DIR=
PIDFILE=

AGENTS_SHORT=()
for ((i=0; i<=$((${#AGENTS[@]}/2-1)); i++)); do
	AGENTS_SHORT+=("$(basename "${AGENTS[$((i*2))]}")")
done


USAGE="Usage: ${SCRIPT_NAME} ACTION
Possible actions:
    start       Start agents
    stop        Stop agents

Currently enabled agents:
    ${AGENTS_SHORT[@]}

Starting without actions will show this screen."

declare -a PIDS


make_rt_dirs() {
	local tmp_dir='/tmp/.pd'
	RT_ROOT="${tmp_dir}/`id -u`"
	mkdir -p "${RT_ROOT}"/{tmp,var/{run,log,tmp}} || echo "mkdir -p failed"
	chmod a+rwxt "${tmp_dir}" 2>/dev/null
}

init_runtime() {
	make_rt_dirs
	PARALLELS_HOME_DIR=${RT_ROOT}
	PIDFILE="${PARALLELS_HOME_DIR}/.prl_agents_pids"
}

# Log to syslog and stderr
# usage: log <error|warning|debug> "MESSAGE"
log() {
	local level=$1
	shift
	case "${level}" in
		error)
			logger -t "${SCRIPT_NAME}" -p user.error -s "$@"
			;;

		warning)
			logger -t "${SCRIPT_NAME}" -p user.warning -s "$@"
			;;

		debug)
			[ "$_DEBUG" == "true" ] && logger -t "${SCRIPT_NAME}" -p user.info -s "$@"
			;;

		*)
			logger -t "${SCRIPT_NAME}" -p user.info -s "${level} $@"
			;;
	esac
}

get_pids() {
	[ ! -f "${PIDFILE}" ] && return
	log "Loading pids from ${PIDFILE}"
	local i=0
	while read pid; do
		PIDS[$i]="${pid}"
		((i++))
	done < "${PIDFILE}"
}

dump_pids() {
	[ -f "${PIDFILE}" ] && rm "${PIDFILE}"
	log "Dump pids to ${PIDFILE}"
	for ((i=0; i<=$((${#AGENTS[@]}/2-1)); i++)); do
		echo "${PIDS[$i]}" >> "${PIDFILE}"
	done
}


is_active() {
	kill -0 $1 2>&1 1>&/dev/null
}

start_agents() {
	get_pids
	for ((i=0; i<=$((${#AGENTS[@]}/2-1)); i++)); do
		# Check for already runned process
		if ! is_active "${PIDS[$i]}"; then
			log "Starting ${AGENTS_SHORT[$i]}..."

			"${AGENTS[$((i*2))]}" ${AGENTS[$((i*2+1))]} 2>&1 1>&/dev/null &
			pid=$!

			sleep "${TIME_FOR_SLEEP}"
			if is_active "${pid}"; then
				PIDS[$i]="${pid}"
				log "${AGENTS_SHORT[$i]} has been started with pid ${PIDS[$i]}"
			else
				log warning "${AGENTS_SHORT[$i]} not started"
				PIDS[$i]=""
			fi
		else
			log "${AGENTS_SHORT[$i]} already started with pid ${PIDS[$i]} and alive"
		fi
	done
	dump_pids
}

stop_agents() {
	get_pids
	for ((i=0; i<=$((${#AGENTS[@]}/2-1)); i++)); do
		if [ -n "${PIDS[$i]}" ]; then
			log "Killing ${AGENTS_SHORT[$i]} (${PIDS[$i]})"
			kill -TERM ${PIDS[$i]}
		else
			log "${AGENTS_SHORT[$i]} (${PIDS[$i]}) not alive"
		fi
	done
	[ -f "${PIDFILE}" ] && rm "${PIDFILE}"
}


init_runtime

if test ! -d "${PARALLELS_HOME_DIR}"; then
	mkdir -p "$PARALLELS_HOME_DIR"
fi

if test ! -w "${PARALLELS_HOME_DIR}"; then
	log error "${PARALLELS_HOME_DIR} is not writable"
	exit 1
fi

case $1 in
	start)
		start_agents
		;;

	stop)
		stop_agents
		;;

	restart)
		stop_agents
		start_agents
		;;

	*)
		echo "${USAGE}"
		;;
esac
